package com.spring.demo.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * Created by YANGHENG940 on 2017/7/20.
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        RestTemplate restTemplate = new RestTemplate(factory);
        for(int i = 0;i<restTemplate.getMessageConverters().size();i++){
            if(restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter){
                restTemplate.getMessageConverters().remove(i);
                StringHttpMessageConverter e = new StringHttpMessageConverter(StandardCharsets.UTF_8);
                restTemplate.getMessageConverters().add(i,e);
            }
        }
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);   //ms
        factory.setConnectTimeout(15000);  //ms
        return factory;
    }
}
